package com.cungmua.app.activity;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.util.Log;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import com.cungmua.app.R;
import com.cungmua.app.base.BaseRequestActivity;
import com.cungmua.app.handler.LoginHandler;
import com.cungmua.app.model.request.LoginRequest;
import com.cungmua.app.model.response.LoginResponse;
import com.cungmua.app.task.LoginTask;
import com.cungmua.app.utils.AppConfig;

/**
 * Created by kelvin.nguyen on 6/23/14.
 */
public class WebLoginActivity extends BaseRequestActivity implements LoginHandler {

    private String method;
    private WebView webView;
    private LoginRequest request;

    @Override
    public int getLayoutResource() {
        return R.layout.activity_webview;
    }

    @Override
    public void updateView() {
        method = getIntent().getExtras().getString(IK_METHOD);
        String endpoint = null;

        if (method.equals(IK_METHOD_YAHOO)) {
            endpoint = AppConfig.getYahooLoginEndpoint();
        } else if (method.equals(IK_METHOD_GOOGLE)) {
            endpoint = AppConfig.getGoogleLoginEndpoint();
        }

        final String resultUrl = "ok://cungmua?";

        final ProgressDialog pd = ProgressDialog.show(this, "Loading...", getString(R.string.loading), true, true);
        //webView.setInitialScale(100);
        webView.getSettings().setSupportZoom(true);
        webView.getSettings().setJavaScriptEnabled(true);
        webView.getSettings().setUseWideViewPort(true);
        webView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                if (url.indexOf(resultUrl) >= 0) {
                    url = url.replace("#","");
                    String[] params = url.replace(resultUrl, "").split("&");

                    loginToServer(method, params);

                    return false;
                }
                return super.shouldOverrideUrlLoading(view, url);
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                if (pd != null && pd.isShowing()) {
                    pd.dismiss();
                }
                super.onPageFinished(view, url);
            }
        });
        webView.loadUrl(endpoint);
    }

    private void loginToServer(String method, String[] params) {
        String uid = params[0];
        String email = params[1];
        String token = params[2];

        request = new LoginRequest(getDeviceId(), getToken());

        request.setAuthToken(token);
        request.setEmail(email);
        request.setAuthType("RESIGN");
        request.setUid(uid);

        Log.d("Token=========:", token);

        LoginTask task = new LoginTask(this, this);
        task.execute(request);
    }

    @Override
    public void loadControls(Bundle savedInstanceState) {
        webView = (WebView) findViewById(R.id.webView);
    }

    @Override
    public void loginSuccess(LoginResponse response) {
        setCurrentUser(response.getData());
        setLastLoginRequest(request);
        setResult(RESULT_OK);
        finish();
    }

    @Override
    public void loginFailed(LoginResponse loginResponse) {
        AlertDialog dialog = new AlertDialog.Builder(this)
                .setMessage(loginResponse.getMessage())
                .setNeutralButton(R.string.ok, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        dialogInterface.dismiss();
                    }
                }).show();
    }
}

